<template>
  <el-breadcrumb :class="{'header-bread': mode === 'header'}" separator-class="el-icon-arrow-right">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item,index) in levelList" :key="item.path">
        <span v-if="item.redirect === 'noRedirect' || index === levelList.length - 1"
          class="no-redirect">{{ item.meta.title }}</span>
        <a v-else @click.prevent="handleLink(item)">{{ item.meta.title }}</a>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
import pathToRegexp from 'path-to-regexp'

export default {
  props: {
    mode: {
      type: String,
      default: 'container',
    },
  },
  data() {
    return {
      levelList: null,
    }
  },
  watch: {
    $route() {
      this.getBreadcrumb()
    },
  },
  created() {
    this.getBreadcrumb()
  },
  methods: {
    getBreadcrumb() {
      let matched = this.$route.matched.filter(
        (item) => item.meta && item.meta.title
      )
      matched = [{ path: '/', meta: { title: '首页' } }].concat(matched)
      this.levelList = matched.filter(
        (item) => item.meta && item.meta.title && item.meta.breadcrumb !== false
      )
    },
    pathCompile(path) {
      const { params } = this.$route
      const toPath = pathToRegexp.compile(path)
      return toPath(params)
    },
    handleLink(item) {
      const { redirect, path } = item
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      this.$router.push(this.pathCompile(path))
    },
  },
}
</script>

<style lang="scss" scoped>
.el-breadcrumb {
  font-size: 16px;
  padding: 12px;
  margin-bottom: 10px;
  border-radius: 4px;
  background: #fff;
  color: #666;
  &.header-bread {
    background: none;
    flex: 1;
    font-size: 14px;
    line-height: 36px;
    height: 60px;
    margin-left: -1px;
    border-left: 1px solid $border-color-lighter;
  }
  .no-redirect {
    color: #999;
    cursor: text;
  }
}
</style>
